package com.riddle.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.riddle.util.StringUtil;

public class User {

	private Long id;
	
	private String name;
	
	private String password;
	
	private String salt;
	
	private boolean locked;

	private List<Role> roles = new ArrayList<Role>();
	
	private String rolesStr = null;
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}

	public boolean isLocked() {
		return locked;
	}

	public void setLocked(boolean locked) {
		this.locked = locked;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public String getRolesStr() {
		if(StringUtil.isNullOrEmpty(rolesStr)) {
			if(getRoles() != null && getRoles().size() > 0) {
				StringBuffer sb = new StringBuffer();
				
				for(Role r : getRoles()) {
					if(r != null) {
						sb.append(r.getId());
						sb.append(",");
					}
				}
				if(sb.length() > 0) {
					rolesStr = sb.toString().substring(0, sb.length() - 1);
				}
			}
		}
		return rolesStr;
	}

	public void setRolesStr(String rolesStr) {
		this.rolesStr = rolesStr;
	}

	public void getRolesAndPermissions(Set<String> roleres, Set<String> permissionres) {
		getRolesAndPermissions(getRoles(), roleres, permissionres);
	}
	
	private void getRolesAndPermissions(List<Role> roles, Set<String> roleres, Set<String> permissionres) {
		for(Role role : roles) {
			roleres.add(role.getAlias());
			for(Permission p : role.getPermissions()) {
				permissionres.add(p.getAlias());
			}
			getRolesAndPermissions(role.getChildren(), roleres, permissionres);
		}
	}
}
